<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/15
 * Time: 11:36
 */
namespace Common\Service;

use Common\Util\ConfigUtils;
use Think\Cache;
use Think\Log;

class WeChatService{
    public $get_access_token_url;

    public function __construct()
    {
        $APP_ID = self::getKey();
        $APP_SECRET = self::getSecret();
        $this->get_access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$APP_ID}&secret={$APP_SECRET}";
    }

    public static function getKey(){
        return ConfigUtils::getConfig("WEIXIN_LITE_APPID");
    }

    public static function getSecret(){
        return ConfigUtils::getConfig("WEIXIN_LITE_SECRET");
    }

    // 获取access_token
    public function getAccessToken(){
        $access_token = S('wechat_mini_program_access_token');
        if (!$access_token){
            $result = $this->httpRequest($this->get_access_token_url);
            $result = json_decode($result, true);
            if (isset($result['errcode'])){
                throw new \Exception('获取access_token失败，' . $result['errmsg']);
            }
            $access_token = $result['access_token'];
            S('wechat_mini_program_access_token', $access_token, 6000);
        }

        return $access_token;
    }

    /**
     * @param $id
     * @throws \Exception
     */
    public function getMiniQrCode($id){
        $access_token = $this->getAccessToken();
        $get_qr_code_url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$access_token}";

        $params = json_encode([
            'path' => "pages/case/case?id={$id}&reach=1&share=1",
            'width' => 640
            ]);
        $return = $this->httpRequest($get_qr_code_url, $params, 'POST');

        $file_name = '/' . time() . '_' . rand(1000, 9999) . '.jpg';
        $prefixPath = 'dmk_bj/';
        $path = 'Upload/' . date('Y-m-d');
        $root = $_SERVER['DOCUMENT_ROOT'];
        is_dir($root .'/'.$prefixPath. $path) or mkdir($root . '/'.$prefixPath.$path,0777,true);

        $err_code = json_decode($return,true)['errcode'];
        $err_msg = json_decode($return,true)['errmsg'];
        if($err_code) {
            Log::record("微信返回" . $return);
            return ['status' => 0,'info' => $err_msg['info']];
        }
  
        $res = file_put_contents($root . '/'.$prefixPath .$path . $file_name,$return);			//	将获取到的二维码图片流保存成图片文件

        if($res===false) return ['status' => 0,'info' => '获取小程序码失败'];
        return ['status' => 1,'info' => $path . $file_name];
    }

    /**
     * @param $id
     * @throws \Exception
     */
    public function sendMsg($msg){
        $access_token = $this->getAccessToken();
        $get_qr_code_url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$access_token}";

        $params = json_encode($msg);
        return $this->httpRequest($get_qr_code_url, $params, 'POST');
    }

    function httpRequest($url, $data='', $method='GET'){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if($method=='POST')
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '')
            {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }
}